package com.itheima.crawler.Task;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.crawler.pojo.Item;
import com.itheima.crawler.service.ItemService;
import com.itheima.crawler.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class ItemTask {

    @Autowired
    private HttpUtils httpUtils;
    @Autowired
    private ItemService itemService;

    public static final ObjectMapper MAPPER = new ObjectMapper();
    private long count=0;

    //设置定时任务执行完成后，再间隔100秒执行一次
    @Scheduled(fixedDelay = 1000 * 100000)
    public void process() throws Exception {
        //分析页面发现访问的地址,页码page从1开始，下一页oage加2
        //String url = "https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&cid2=653&cid3=655&s=5760&click=0&page=";
        String url="https://search.jd.com/Search?keyword=手机&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=手机&cid2=653&cid3=655&s=1&click=0&page=";
        //遍历执行，获取所有的数据
        for (int i = 1; i < 10; i = i + 2) {
            log.info("Page: {} ************************************************************ ",i);
            //发起请求进行访问，获取页面数据,先访问第一页
            String html = this.httpUtils.getHtml(url + i);
            //解析页面数据，保存数据到数据库中
            this.parseHtml(html);
            log.info("Page: {} ************************************************************ length: {}",i,html.length());

        }
        System.out.println("执行完成");
    }


    //解析页面，并把数据保存到数据库中
    private void parseHtml(String html) throws Exception {
        //使用jsoup解析页面
        Document document = Jsoup.parse(html);

        //获取商品数据
        Elements spus = document.select("div#J_goodsList > ul > li");

        //遍历商品spu数据
        for (Element spuEle : spus) {

            //获取商品spu
            count=count+1;
            Long spuId = Long.parseLong(spuEle.attr("data-spu"));
            log.info("===================处理item：spu={}==================={}",spuId,count);
            //获取商品sku数据
            Elements skus = spuEle.select("li.ps-item img");
            for (Element skuEle : skus) {
                //获取商品sku
                Long skuId = Long.parseLong(skuEle.attr("data-sku"));
                log.info("------------处理item：spu={} ---> sku={}------------",spuId,skuId);
                //判断商品是否被抓取过，可以根据sku判断
                Item param = new Item();
                param.setSku(skuId);
                List<Item> list = this.itemService.findAll(param);
                //判断是否查询到结果
                if (list.size() > 0) {
                    //如果有结果，表示商品已下载，进行下一次遍历
                    log.info("item: skuId= {} 已经下载....",skuId);
                    continue;
                }

                //保存商品数据，声明商品对象
                Item item = new Item();

                //商品spu
                item.setSpu(spuId);
                //商品sku
                item.setSku(skuId);
                //商品url地址
                item.setUrl("https://item.jd.com/" + skuId + ".html");
                //创建时间
                item.setCreated(new Date());
                //修改时间
                item.setUpdated(item.getCreated());


                //获取商品标题;
                log.info("item uri= {}", item.getUrl());
                String itemHtml = this.httpUtils.getHtml(item.getUrl());
                String title = Jsoup.parse(itemHtml).select("div.sku-name").text();
                item.setTitle(title);

                //获取商品价格
                String priceUrl = "https://p.3.cn/prices/mgets?skuIds=J_"+skuId;
                log.info("price uri= {}",priceUrl );
                String priceJson = this.httpUtils.getHtml(priceUrl);

                //解析json数据获取商品价格
                double price = MAPPER.readTree(priceJson).get(0).get("p").asDouble();
                item.setPrice(price);

                //获取图片地址
                String pic="";
                if(!StringUtils.equals("", skuEle.attr("data-lazy-img"))) {
                     pic = "https:" + skuEle.attr("data-lazy-img").replace("/n9/", "/n1/");
                }else {
                     pic = "https:" + skuEle.attr("data-lazy-img-slave").replace("/n9/", "/n1/");
                }
                //下载图片
                log.info("img uri={}", pic);
                String picName = this.httpUtils.getImage(pic);
                item.setPic(picName);
                log.info("保存item： {}",item.toString());
                //保存商品数据
                this.itemService.save(item);
            }
        }
    }
}